package com.analysis.server.service;

import cn.hutool.core.util.ObjUtil;
import com.analysis.server.model.LogTemplate;
import com.analysis.server.model.SlowSqlResult;
import com.analysis.server.repository.ILogTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 日志分析服务类 - 高性能优化版本
 * 用于分析MyBatis日志文件，检测慢SQL
 */
@Service
public class LogAnalysisService {
    
    private static final Logger logger = LoggerFactory.getLogger(LogAnalysisService.class);
    
    @Autowired
    private ILogTemplateService logTemplateRepository;
    
    @Autowired
    private LogAnalysisPerformanceMonitor performanceMonitor;
    
    // 日志时间格式
    private static final DateTimeFormatter LOG_TIME_FORMATTER = 
        DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    // 正则表达式模式 - 预编译以提高性能
    private static final Pattern PREPARING_PATTERN = 
        Pattern.compile("(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}) \\[.*?\\] DEBUG (.*?) - ==>  Preparing: (.+)");
    
    private static final Pattern PARAMETERS_PATTERN = 
        Pattern.compile("(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}) \\[.*?\\] DEBUG (.*?) - ==> Parameters: (.+)");
    
    private static final Pattern TOTAL_PATTERN = 
        Pattern.compile("(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}) \\[.*?\\] TRACE (.*?) - <==      Total: (.+)");
    
    private static final Pattern ROW_PATTERN = 
        Pattern.compile("(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}) \\[.*?\\] TRACE (.*?) - <==        Row: (.+)");
    
    // 慢SQL阈值（毫秒）
    private static final long SLOW_SQL_THRESHOLD_30S = 30000;  // 30秒
    private static final long SLOW_SQL_THRESHOLD_1MIN = 60000; // 1分钟
    
    // 性能优化配置
    private static final int MAX_CACHE_SIZE = 10000; // 最大缓存SQL数量
    private static final long CACHE_CLEANUP_INTERVAL = 300000; // 缓存清理间隔(5分钟)
    private static final int THREAD_POOL_SIZE = Runtime.getRuntime().availableProcessors();
    private static final int BATCH_SIZE = 1000; // 批处理大小
    
    // 线程池
    private final ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
    
    /**
     * 高性能日志文件分析 - 优化版本
     * @param file 上传的日志文件
     * @return 慢SQL分析结果列表
     */
    public List<SlowSqlResult> analyzeLogFile(MultipartFile file) throws IOException {
        long startTime = System.currentTimeMillis();
        
        // 启动性能监控
        performanceMonitor.startMonitoring();
        performanceMonitor.recordFileStart(file.getSize());
        
        logger.debug("开始分析日志文件，大小: {} bytes", file.getSize());
        
        // 使用ConcurrentHashMap提高并发性能
        Map<String, SqlExecutionInfo> sqlExecutionMap = new ConcurrentHashMap<>();
        List<SlowSqlResult> slowSqlResults = Collections.synchronizedList(new ArrayList<>());
        
        // 启动缓存清理任务
        ScheduledExecutorService cleanupExecutor = Executors.newSingleThreadScheduledExecutor();
        cleanupExecutor.scheduleAtFixedRate(() -> cleanupExpiredCache(sqlExecutionMap), 
            CACHE_CLEANUP_INTERVAL, CACHE_CLEANUP_INTERVAL, TimeUnit.MILLISECONDS);
        
        try {
            // 使用NIO读取文件，提高I/O性能
            List<String> lines = readFileLines(file);
            
            // 分批处理，避免内存溢出
            List<Future<Void>> futures = new ArrayList<>();
            for (int i = 0; i < lines.size(); i += BATCH_SIZE) {
                final int startIndex = i;
                int endIndex = Math.min(i + BATCH_SIZE, lines.size());
                List<String> batch = lines.subList(i, endIndex);
                
                Future<Void> future = executorService.submit(() -> {
                    processBatch(batch, startIndex, sqlExecutionMap, slowSqlResults);
                    return null;
                });
                futures.add(future);
            }
            
            // 等待所有任务完成
            for (Future<Void> future : futures) {
                try {
                    future.get();
                } catch (Exception e) {
                    logger.error("批处理任务执行失败", e);
                    performanceMonitor.recordError("批处理失败", e.getMessage());
                }
            }
            
            // 处理剩余的未完成SQL
            processRemainingSqls(sqlExecutionMap, slowSqlResults);
            
        } finally {
            cleanupExecutor.shutdown();
        }
        
        long processingTime = System.currentTimeMillis() - startTime;
        performanceMonitor.recordFileComplete(file.getSize(), processingTime, slowSqlResults.size());
        
        logger.debug("日志分析完成，发现慢SQL数量: {}", slowSqlResults.size());
        
        // 生成性能报告
        performanceMonitor.generatePerformanceReport();
        
        return new ArrayList<>(slowSqlResults);
    }
    
    /**
     * 获取性能监控快照
     */
    public LogAnalysisPerformanceMonitor.PerformanceSnapshot getPerformanceSnapshot() {
        return performanceMonitor.getSnapshot();
    }
    
    /**
     * 使用NIO高效读取文件
     */
    private List<String> readFileLines(MultipartFile file) throws IOException {
        List<String> lines = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {
            
            String line;
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }
        }
        return lines;
    }
    
    /**
     * 批处理日志行
     */
    private void processBatch(List<String> lines, int startIndex, 
                            Map<String, SqlExecutionInfo> sqlExecutionMap, 
                            List<SlowSqlResult> slowSqlResults) {
        
        for (int i = 0; i < lines.size(); i++) {
            String line = lines.get(i);
            int lineNumber = startIndex + i + 1;
            
            // 记录行处理
            performanceMonitor.recordLineProcessed();
            
            // 快速预判断，减少正则匹配
            if (!isRelevantLogLine(line)) {
                continue;
            }
            
            processLogLine(line, lineNumber, sqlExecutionMap, slowSqlResults);
        }
    }
    
    /**
     * 快速预判断是否为相关日志行
     */
    private boolean isRelevantLogLine(String line) {
        return line.contains("Preparing:") || line.contains("Parameters:") || 
               line.contains("Total:") || line.contains("Row:");
    }
    
    /**
     * 处理单行日志
     */
    private void processLogLine(String line, int lineNumber, 
                              Map<String, SqlExecutionInfo> sqlExecutionMap, 
                              List<SlowSqlResult> slowSqlResults) {
        
        // 解析Preparing行
        Matcher preparingMatcher = PREPARING_PATTERN.matcher(line);
        if (preparingMatcher.find()) {
            performanceMonitor.recordRegexMatch(true);
            processPreparingLine(preparingMatcher, lineNumber, line, sqlExecutionMap);
            return;
        }
        
        // 解析Parameters行
        Matcher parametersMatcher = PARAMETERS_PATTERN.matcher(line);
        if (parametersMatcher.find()) {
            performanceMonitor.recordRegexMatch(true);
            processParametersLine(parametersMatcher, sqlExecutionMap);
            return;
        }
        
        // 解析Total行（SQL执行完成）
        Matcher totalMatcher = TOTAL_PATTERN.matcher(line);
        if (totalMatcher.find()) {
            performanceMonitor.recordRegexMatch(true);
            processCompletionLine(totalMatcher, lineNumber, line, sqlExecutionMap, slowSqlResults);
            return;
        }
        
        // 解析Row行（SQL执行完成）
        Matcher rowMatcher = ROW_PATTERN.matcher(line);
        if (rowMatcher.find()) {
            performanceMonitor.recordRegexMatch(true);
            processCompletionLine(rowMatcher, lineNumber, line, sqlExecutionMap, slowSqlResults);
        } else {
            // 记录正则匹配失败
            performanceMonitor.recordRegexMatch(false);
        }
    }
    
    /**
     * 处理Preparing行
     */
    private void processPreparingLine(Matcher matcher, int lineNumber, String line, 
                                    Map<String, SqlExecutionInfo> sqlExecutionMap) {
        String timestamp = matcher.group(1);
        String mapperName = matcher.group(2);
        String sql = matcher.group(3);
        
        LocalDateTime startTime = parseDateTime(timestamp);
        if (startTime != null) {
            // 使用更稳定的键生成策略
            String sqlKey = generateStableKey(mapperName, sql, startTime);
            
            // 检查缓存大小，避免内存溢出
            if (sqlExecutionMap.size() >= MAX_CACHE_SIZE) {
                cleanupOldestEntries(sqlExecutionMap);
            }
            
            sqlExecutionMap.put(sqlKey, new SqlExecutionInfo(sql, mapperName, startTime, lineNumber, line));
        }
    }
    
    /**
     * 处理Parameters行
     */
    private void processParametersLine(Matcher matcher, Map<String, SqlExecutionInfo> sqlExecutionMap) {
        String timestamp = matcher.group(1);
        String mapperName = matcher.group(2);
        String parameters = matcher.group(3);
        
        LocalDateTime paramTime = parseDateTime(timestamp);
        if (paramTime != null) {
            // 查找最近的匹配SQL
            SqlExecutionInfo info = findMatchingSql(sqlExecutionMap, mapperName, paramTime);
            if (info != null) {
                info.setParameters(parameters);
            }
        }
    }
    
    /**
     * 处理完成行（Total或Row）
     */
    private void processCompletionLine(Matcher matcher, int lineNumber, String line,
                                     Map<String, SqlExecutionInfo> sqlExecutionMap, 
                                     List<SlowSqlResult> slowSqlResults) {
        String timestamp = matcher.group(1);
        String mapperName = matcher.group(2);
        
        LocalDateTime endTime = parseDateTime(timestamp);
        if (endTime != null) {
            processSqlCompletion(sqlExecutionMap, mapperName, endTime, lineNumber, line, slowSqlResults);
        }
    }
    
    /**
     * 生成稳定的键
     */
    private String generateStableKey(String mapperName, String sql, LocalDateTime startTime) {
        return mapperName + ":" + startTime.toEpochSecond(java.time.ZoneOffset.UTC) + ":" + sql.hashCode();
    }
    
    /**
     * 查找匹配的SQL
     */
    private SqlExecutionInfo findMatchingSql(Map<String, SqlExecutionInfo> sqlExecutionMap, 
                                           String mapperName, LocalDateTime paramTime) {
        return sqlExecutionMap.values().stream()
            .filter(info -> info.getMapperName().equals(mapperName))
            .filter(info -> info.getStartTime() != null && 
                          Math.abs(java.time.Duration.between(info.getStartTime(), paramTime).toMillis()) < 1000)
            .findFirst()
            .orElse(null);
    }
    
    /**
     * 清理过期缓存
     */
    private void cleanupExpiredCache(Map<String, SqlExecutionInfo> sqlExecutionMap) {
        long currentTime = System.currentTimeMillis();
        long expireTime = currentTime - 300000; // 5分钟过期
        
        int beforeSize = sqlExecutionMap.size();
        
        sqlExecutionMap.entrySet().removeIf(entry -> {
            SqlExecutionInfo info = entry.getValue();
            return info.getStartTime() != null && 
                   info.getStartTime().toEpochSecond(java.time.ZoneOffset.UTC) * 1000 < expireTime;
        });
        
        int afterSize = sqlExecutionMap.size();
        int evictedCount = beforeSize - afterSize;
        
        // 记录缓存操作
        performanceMonitor.recordCacheOperation(afterSize, evictedCount);
        
        logger.debug("缓存清理完成，当前缓存大小: {}", afterSize);
    }
    
    /**
     * 清理最旧的条目
     */
    private void cleanupOldestEntries(Map<String, SqlExecutionInfo> sqlExecutionMap) {
        if (sqlExecutionMap.size() <= MAX_CACHE_SIZE / 2) {
            return;
        }
        
        // 按开始时间排序，移除最旧的条目
        List<Map.Entry<String, SqlExecutionInfo>> sortedEntries = new ArrayList<>(sqlExecutionMap.entrySet());
        sortedEntries.sort((e1, e2) -> {
            LocalDateTime time1 = e1.getValue().getStartTime();
            LocalDateTime time2 = e2.getValue().getStartTime();
            if (time1 == null && time2 == null) return 0;
            if (time1 == null) return 1;
            if (time2 == null) return -1;
            return time1.compareTo(time2);
        });
        
        int removeCount = sortedEntries.size() - MAX_CACHE_SIZE / 2;
        for (int i = 0; i < removeCount; i++) {
            sqlExecutionMap.remove(sortedEntries.get(i).getKey());
        }
        
        // 记录缓存操作
        performanceMonitor.recordCacheOperation(sqlExecutionMap.size(), removeCount);
        
        logger.warn("清理了 {} 个旧条目，当前缓存大小: {}", removeCount, sqlExecutionMap.size());
    }
    
    /**
     * 处理剩余的未完成SQL
     */
    private void processRemainingSqls(Map<String, SqlExecutionInfo> sqlExecutionMap, 
                                    List<SlowSqlResult> slowSqlResults) {
        LocalDateTime now = LocalDateTime.now();
        for (SqlExecutionInfo info : sqlExecutionMap.values()) {
            if (info.getStartTime() != null) {
                long duration = java.time.Duration.between(info.getStartTime(), now).toMillis();
                if (duration >= SLOW_SQL_THRESHOLD_30S) {
                    SlowSqlResult result = new SlowSqlResult(
                        info.getSql(),
                        info.getStartTime(),
                        now,
                        info.getMapperName(),
                        info.getParameters(),
                        info.getLineNumber(),
                        info.getLogLine()
                    );
                    slowSqlResults.add(result);
                }
            }
        }
    }
    
    /**
     * 处理SQL执行完成 - 优化版本
     */
    private void processSqlCompletion(Map<String, SqlExecutionInfo> sqlExecutionMap, 
                                    String mapperName, LocalDateTime endTime, 
                                    int lineNumber, String logLine, 
                                    List<SlowSqlResult> slowSqlResults) {
        
        // 查找对应的SQL执行信息
        SqlExecutionInfo info = findMatchingSql(sqlExecutionMap, mapperName, endTime);
        
        if (info != null) {
            long duration = java.time.Duration.between(info.getStartTime(), endTime).toMillis();
            
            // 检查是否为慢SQL
            if (duration >= SLOW_SQL_THRESHOLD_30S) {
                SlowSqlResult result = new SlowSqlResult(
                    info.getSql(),
                    info.getStartTime(),
                    endTime,
                    info.getMapperName(),
                    info.getParameters(),
                    info.getLineNumber(),
                    info.getLogLine()
                );
                slowSqlResults.add(result);
            }
            
            // 从缓存中移除已完成的SQL
            sqlExecutionMap.remove(generateStableKey(info.getMapperName(), info.getSql(), info.getStartTime()));
        }
    }
    
    /**
     * 解析日期时间字符串 - 优化版本
     */
    private LocalDateTime parseDateTime(String timestamp) {
        try {
            return LocalDateTime.parse(timestamp, LOG_TIME_FORMATTER);
        } catch (DateTimeParseException e) {
            // 减少日志输出，只在DEBUG级别记录
            if (logger.isDebugEnabled()) {
                logger.debug("时间解析失败: {}", timestamp);
            }
            return null;
        }
    }
    
    /**
     * SQL执行信息内部类 - 优化版本
     */
    private static class SqlExecutionInfo {
        private final String sql;
        private final String mapperName;
        private final LocalDateTime startTime;
        private String parameters;
        private final int lineNumber;
        private final String logLine;
        
        public SqlExecutionInfo(String sql, String mapperName, LocalDateTime startTime, 
                              int lineNumber, String logLine) {
            this.sql = sql;
            this.mapperName = mapperName;
            this.startTime = startTime;
            this.lineNumber = lineNumber;
            this.logLine = logLine;
        }
        
        // Getters and Setters
        public String getSql() { return sql; }
        public String getMapperName() { return mapperName; }
        public LocalDateTime getStartTime() { return startTime; }
        public String getParameters() { return parameters; }
        public void setParameters(String parameters) { this.parameters = parameters; }
        public int getLineNumber() { return lineNumber; }
        public String getLogLine() { return logLine; }
    }
    /**
     * 根据模板动态解析日志文件（使用数据库中保存的正则表达式）
     */
    public List<SlowSqlResult> analyzeLogFileWithTemplate(MultipartFile file, Long templateId) throws IOException {
        long startTime = System.currentTimeMillis();
        
        // 启动性能监控
        performanceMonitor.startMonitoring();
        performanceMonitor.recordFileStart(file.getSize());
        
        LogTemplate template = logTemplateRepository.getLogTemplateById(templateId);
        if (ObjUtil.isNull(template)) throw new IllegalArgumentException("模板不存在");

        logger.debug("=== 开始分析日志文件 ===");
        logger.debug("模板ID: {}", templateId);
        logger.debug("模板名称: {}", template.getName());
        logger.debug("Preparing正则: {}", template.getPreparingRegex());
        logger.debug("Parameters正则: {}", template.getParametersRegex());
        logger.debug("Total正则: {}", template.getTotalRegex());
        logger.debug("线程匹配策略: {}", template.getThreadMatchingStrategy());

        // 使用数据库中保存的正则表达式
        Pattern preparingPattern = Pattern.compile(template.getPreparingRegex());
        Pattern parametersPattern = Pattern.compile(template.getParametersRegex());
        Pattern totalPattern = Pattern.compile(template.getTotalRegex());

        List<SlowSqlResult> slowSqlResults = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream(), "UTF-8"))) {
            String line;
            int lineNumber = 0;
            LocalDate today = LocalDate.now();
            // 使用更智能的存储结构：Map<线程名, Map<类名, SqlExecutionInfo>>
            Map<String, Map<String, SqlExecutionInfo>> threadSqlMap = new HashMap<>();

            while ((line = reader.readLine()) != null) {
                lineNumber++;
                
                // 记录行处理
                performanceMonitor.recordLineProcessed();

                // 尝试匹配 Preparing 行
                Matcher preparingMatcher = preparingPattern.matcher(line);
                if (preparingMatcher.find()) {
                    performanceMonitor.recordRegexMatch(true);
                    logger.debug("=== 匹配 Preparing 行 ===");
                    logger.debug("行号: {}", lineNumber);
                    logger.debug("日志内容: {}", line);

                    String timeStr = getGroupSafely(preparingMatcher, "time");
                    String sql = getGroupSafely(preparingMatcher, "sql");
                    String mapperName = getGroupSafely(preparingMatcher, "class");
                    String thread = getGroupSafely(preparingMatcher, "thread");

                    logger.debug("提取字段 - 时间: {}, SQL: {}, 类名: {}, 线程: {}", timeStr, sql, mapperName, thread);

                    LocalDateTime time = parseTimeString(timeStr, today);

                    if (sql != null && time != null) {
                        // 为每个线程创建独立的类名映射
                        threadSqlMap.computeIfAbsent(thread, k -> new HashMap<>())
                                   .put(mapperName, new SqlExecutionInfo(sql, mapperName, time, lineNumber, line));
                        logger.debug("记录SQL开始 - 线程: {}, 类名: {}, SQL: {}", thread, mapperName, sql);
                        logger.debug("当前线程数: {}, 总SQL数: {}", threadSqlMap.size(), 
                                  threadSqlMap.values().stream().mapToInt(Map::size).sum());
                    }
                    continue;
                }

                // 尝试匹配 Parameters 行
                Matcher parametersMatcher = parametersPattern.matcher(line);
                if (parametersMatcher.find()) {
                    performanceMonitor.recordRegexMatch(true);
                    logger.debug("=== 匹配 Parameters 行 ===");
                    logger.debug("行号: {}", lineNumber);
                    logger.debug("日志内容: {}", line);

                    String timeStr = getGroupSafely(parametersMatcher, "time");
                    String params = getGroupSafely(parametersMatcher, "params");
                    String mapperName = getGroupSafely(parametersMatcher, "class");
                    String thread = getGroupSafely(parametersMatcher, "thread");

                    logger.debug("提取字段 - 时间: {}, 参数: {}, 类名: {}, 线程: {}", timeStr, params, mapperName, thread);

                    if (params == null || params.trim().isEmpty()) {
                        params = extractParametersManually(line);
                        logger.debug("手动提取参数: {}", params);
                    }

                    if (params != null && !params.trim().isEmpty()) {
                        Map<String, SqlExecutionInfo> classMap = threadSqlMap.get(thread);
                        if (classMap != null) {
                            SqlExecutionInfo info = classMap.get(mapperName);
                            if (info != null) {
                                info.setParameters(params);
                                logger.debug("✓ 成功更新参数 - 线程: {}, 类名: {}, 参数: {}", thread, mapperName, params);
                            } else {
                                logger.debug("✗ 未找到对应的SQL执行信息 - 线程: {}, 类名: {}", thread, mapperName);
                            }
                        } else {
                            logger.debug("✗ 未找到线程的SQL执行信息 - 线程: {}", thread);
                        }
                    } else {
                        logger.warn("⚠ 参数提取失败，跳过此行");
                    }
                    continue;
                }

                // 尝试匹配 Total/Row 行
                Matcher totalMatcher = totalPattern.matcher(line);
                if (totalMatcher.find()) {
                    performanceMonitor.recordRegexMatch(true);
                    logger.debug("=== 匹配 Total/Row 行 ===");
                    logger.debug("行号: {}", lineNumber);
                    logger.debug("日志内容: {}", line);

                    String timeStr = getGroupSafely(totalMatcher, "time");
                    String mapperName = getGroupSafely(totalMatcher, "class");
                    String thread = getGroupSafely(totalMatcher, "thread");

                    logger.debug("提取字段 - 时间: {}, 类名: {}, 线程: {}", timeStr, mapperName, thread);

                    LocalDateTime endTime = parseTimeString(timeStr, today);

                    if (endTime != null) {
                        Map<String, SqlExecutionInfo> classMap = threadSqlMap.get(thread);
                        if (classMap != null) {
                            SqlExecutionInfo foundInfo = classMap.get(mapperName);

                            if (foundInfo != null && foundInfo.getStartTime() != null) {
                                long duration = java.time.Duration.between(foundInfo.getStartTime(), endTime).toMillis();
                                logger.debug("SQL完成 - SQL: {}, 耗时: {}ms, 参数: {}", foundInfo.getSql(), duration, foundInfo.getParameters());

                                if (duration >= template.getSqlTimeoutThreshold()) {
                                    SlowSqlResult result = new SlowSqlResult(
                                        foundInfo.getSql(),
                                        foundInfo.getStartTime(),
                                        endTime,
                                        foundInfo.getMapperName(),
                                        foundInfo.getParameters(),
                                        foundInfo.getLineNumber(),
                                        foundInfo.getLogLine()
                                    );
                                    slowSqlResults.add(result);
                                    logger.debug("✓ 发现慢SQL - SQL: {}, 耗时: {}ms", foundInfo.getSql(), duration);
                                }
                            } else {
                                logger.debug("✗ 未找到对应的SQL执行信息 - 线程: {}, 类名: {}", thread, mapperName);
                            }

                            // 移除已完成的SQL
                            classMap.remove(mapperName);
                            
                            // 如果线程没有更多SQL，清理线程记录
                            if (classMap.isEmpty()) {
                                threadSqlMap.remove(thread);
                            }
                        } else {
                            logger.debug("✗ 未找到线程的SQL执行信息 - 线程: {}", thread);
                        }
                    }
                } else {
                    // 记录正则匹配失败
                    performanceMonitor.recordRegexMatch(false);
                }
            }
        }

        long processingTime = System.currentTimeMillis() - startTime;
        performanceMonitor.recordFileComplete(file.getSize(), processingTime, slowSqlResults.size());
        
        // 生成性能报告
        performanceMonitor.generatePerformanceReport();

        logger.debug("=== 分析完成 ===");
        logger.debug("发现慢SQL数量: {}", slowSqlResults.size());
        return slowSqlResults;
    }

    /**
     * 手动提取参数（当正则表达式失败时的备用方案）
     */
    private String extractParametersManually(String line) {
        try {
            int startIndex = line.indexOf("==> Parameters: ");
            if (startIndex != -1) {
                String params = line.substring(startIndex + "==> Parameters: ".length()).trim();
                logger.debug("手动提取参数: {}", params);
                return params;
            }
        } catch (Exception e) {
            logger.error("手动提取参数失败: {}", e.getMessage());
        }
        return null;
    }

    /**
     * 测试模板正则表达式
     */
    public List<Map<String, Object>> testTemplateRegex(LogTemplate template, String logText) {
        List<Map<String, Object>> results = new ArrayList<>();

        if (template.getPreparingRegex() != null && !template.getPreparingRegex().isEmpty()) {
            Map<String, Object> preparingResult = testRegex(template.getPreparingRegex(), logText, "Preparing");
            results.add(preparingResult);
        }

        if (template.getParametersRegex() != null && !template.getParametersRegex().isEmpty()) {
            Map<String, Object> parametersResult = testRegex(template.getParametersRegex(), logText, "Parameters");
            results.add(parametersResult);
        }

        if (template.getTotalRegex() != null && !template.getTotalRegex().isEmpty()) {
            Map<String, Object> totalResult = testRegex(template.getTotalRegex(), logText, "Total");
            results.add(totalResult);
        }

        return results;
    }

    /**
     * 测试单个正则表达式
     */
    private Map<String, Object> testRegex(String regex, String logText, String type) {
        Map<String, Object> result = new HashMap<>();
        result.put("type", type);

        try {
            // 对于时间字段，尝试多种时间格式的正则表达式
            String adjustedRegex = adjustTimeRegex(regex);
            
            logger.debug("测试类型: {}", type);
            logger.debug("测试文本: {}", logText);
            logger.debug("原始正则: {}", regex);
            logger.debug("调整后正则: {}", adjustedRegex);
            
            Pattern pattern = Pattern.compile(adjustedRegex);
            Matcher matcher = pattern.matcher(logText);

            if (matcher.find()) {
                result.put("matched", true);

                List<Map<String, String>> fields = new ArrayList<>();
                
                // 提取命名捕获组名称（使用原始正则表达式）
                List<String> groupNames = extractNamedGroups(regex);
                
                // 按位置获取捕获组值（与前端逻辑保持一致）
                for (int i = 0; i < groupNames.size(); i++) {
                    String groupName = groupNames.get(i);
                    String value = matcher.group(i + 1); // 按位置获取，从1开始
                    
                    if (value != null) {
                        Map<String, String> field = new HashMap<>();
                        field.put("name", groupName);
                        field.put("value", value);
                        fields.add(field);
                        logger.debug("提取字段: {} = {}", groupName, value);
                    }
                }

                result.put("fields", fields);
            } else {
                result.put("matched", false);
                result.put("fields", new ArrayList<>());
                logger.debug("正则匹配失败");
            }
        } catch (Exception e) {
            result.put("matched", false);
            result.put("error", e.getMessage());
            result.put("fields", new ArrayList<>());
            logger.error("正则测试异常: {}", e.getMessage());
        }

        return result;
    }

    /**
     * 调整时间正则表达式以支持多种时间格式
     */
    private String adjustTimeRegex(String regex) {
        // 支持以下时间格式：
        // 1. 2025-07-12 10:00:00:000 (带毫秒，冒号分隔)
        // 2. 2025-07-12 10:00:00.000 (带毫秒，点分隔)
        // 3. 2025-07-12 10:00:00 (不带毫秒)
        
        // 将严格的时间格式改为灵活格式
        String adjustedRegex = regex.replaceAll(
            "\\(\\?<time>\\\\d\\{4\\}-\\\\d\\{2\\}-\\\\d\\{2\\} \\\\d\\{2\\}:\\\\d\\{2\\}:\\\\d\\{2\\}:\\\\d\\{3\\}\\)",
            "(?<time>\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}(?::\\d{3}|\\.\\d{3})?)"
        );
        
        // 如果上面的替换没有生效，尝试匹配不带毫秒的格式
        if (adjustedRegex.equals(regex)) {
            adjustedRegex = regex.replaceAll(
                "\\(\\?<time>\\\\d\\{4\\}-\\\\d\\{2\\}-\\\\d\\{2\\} \\\\d\\{2\\}:\\\\d\\{2\\}:\\\\d\\{2\\}\\)",
                "(?<time>\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}(?::\\d{3}|\\.\\d{3})?)"
            );
        }
        
        // 如果还是没有替换，尝试更宽松的匹配
        if (adjustedRegex.equals(regex)) {
            adjustedRegex = regex.replaceAll(
                "\\\\d\\{4\\}-\\\\d\\{2\\}-\\\\d\\{2\\} \\\\d\\{2\\}:\\\\d\\{2\\}:\\\\d\\{2\\}:\\\\d\\{3\\}",
                "\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}(?::\\d{3}|\\.\\d{3})?"
            );
        }
        
        logger.debug("原始正则: {}", regex);
        logger.debug("调整后正则: {}", adjustedRegex);
        
        return adjustedRegex;
    }

    /**
     * 提取正则表达式中的命名捕获组名称
     */
    private List<String> extractNamedGroups(String regex) {
        List<String> groupNames = new ArrayList<>();
        Pattern groupPattern = Pattern.compile("\\(\\?<(\\w+)>");
        Matcher groupMatcher = groupPattern.matcher(regex);
        
        while (groupMatcher.find()) {
            groupNames.add(groupMatcher.group(1));
        }
        
        return groupNames;
    }

    /**
     * 根据线程匹配策略生成键
     */
    private String generateKey(String thread, String mapperName, String strategy) {
        if (thread == null) return mapperName;

        switch (strategy) {
            case "prefix":
                return thread.split("-")[0] + "|" + mapperName;
            case "contains":
                return thread + "|" + mapperName;
            case "exact":
            default:
                return thread + "|" + mapperName;
        }
    }

    /**
     * 创建 Preparing 行的正则表达式
     */
    private String createPreparingRegex(String template) {
        return templateToRegex(template);
    }

    /**
     * 创建 Parameters 行的正则表达式
     */
    private String createParametersRegex(String template) {
        String parametersTemplate = template.replace("Preparing:", "Parameters:");
        return templateToRegex(parametersTemplate);
    }

    /**
     * 创建 Total/Row 行的正则表达式
     */
    private String createTotalRegex(String template) {
        String totalTemplate = template.replace("==>  Preparing:", "<==      Total:");
        return templateToRegex(totalTemplate);
    }

    /**
     * 安全地获取正则分组，如果分组不存在返回null
     */
    private String getGroupSafely(Matcher matcher, String groupName) {
        try {
            return matcher.group(groupName);
        } catch (IllegalArgumentException e) {
            return null;
        }
    }

    /**
     * 从模板中提取所有字段名
     */
    private Set<String> extractTemplateFields(String template) {
        Set<String> fields = new HashSet<>();
        Pattern fieldPattern = Pattern.compile("\\{(\\w+)}");
        Matcher matcher = fieldPattern.matcher(template);
        while (matcher.find()) {
            fields.add(matcher.group(1));
        }
        return fields;
    }

    /**
     * 解析时间字符串
     */
    private LocalDateTime parseTimeString(String timeStr, LocalDate today) {
        if (timeStr == null) return null;

        try {
            // 支持多种时间格式
            if (timeStr.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}:\\d{3}")) {
                // 格式: 2025-07-12 10:00:00:000
                return LocalDateTime.parse(timeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS"));
            } else if (timeStr.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}\\.\\d{3}")) {
                // 格式: 2025-07-12 10:00:00.000
                return LocalDateTime.parse(timeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
            } else if (timeStr.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}")) {
                // 格式: 2025-07-12 10:00:00
                return LocalDateTime.parse(timeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            } else if (timeStr.matches("\\d{2}:\\d{2}:\\d{2}\\.\\d{3}")) {
                // 格式: 10:00:00.000
                return LocalDateTime.of(today, LocalTime.parse(timeStr, DateTimeFormatter.ofPattern("HH:mm:ss.SSS")));
            } else if (timeStr.matches("\\d{2}:\\d{2}:\\d{2}")) {
                // 格式: 10:00:00
                return LocalDateTime.of(today, LocalTime.parse(timeStr, DateTimeFormatter.ofPattern("HH:mm:ss")));
            } else {
                logger.warn("不支持的时间格式: {}", timeStr);
                return null;
            }
        } catch (Exception e) {
            logger.error("时间解析失败: {}, 错误: {}", timeStr, e.getMessage());
            return null;
        }
    }



    // 模板转正则
    public static String templateToRegex(String template) {
        String regex = template.replace("[", "\\[")
                .replace("]", "\\]")
                .replace(".", "\\.");
        Pattern fieldPattern = Pattern.compile("\\{(\\w+)}");
        Matcher matcher = fieldPattern.matcher(regex);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String field = matcher.group(1);
            String replacement;
            
            // 根据字段类型生成不同的正则表达式
            switch (field) {
                case "time":
                    // 支持多种时间格式：2025-07-12 10:00:00:000 或 2025-07-12 10:00:00.000 或 2025-07-12 10:00:00
                    replacement = "(?<time>\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}(?::\\d{3}|\\.\\d{3})?)";
                    break;
                case "thread":
                    replacement = "(?<thread>[^\\]]+)";
                    break;
                case "level":
                    replacement = "(?<level>\\w+)";
                    break;
                case "class":
                    replacement = "(?<class>[\\w\\.]+)";
                    break;
                case "sql":
                    replacement = "(?<sql>.+)";
                    break;
                case "params":
                    replacement = "(?<params>.+)";
                    break;
                case "total":
                    replacement = "(?<total>\\d+)";
                    break;
                case "row":
                    replacement = "(?<row>.+)";
                    break;
                case "msg":
                    replacement = "(?<msg>.+)";
                    break;
                default:
                    replacement = "(?<" + field + ">.*?)";
                    break;
            }
            matcher.appendReplacement(sb, replacement);
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 手动重置性能监控指标
     */
    public void resetPerformanceMetrics() {
        performanceMonitor.resetMetrics();
    }
}